import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Badge, Icon } from 'antd';
import { stringify } from 'qs';
import router from 'umi/router';
import moment from 'moment';
import ManageList from '@/components/ManageList';
import SelectForm from '@/components/SelectForm';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import AntdDatePicker from '@/components/AntdDatePicker';
import AntdFormItem from '@/components/AntdFormItem';
import SearchSelect from '@/components/SearchSelect';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import FileReader from '@/components/FileReader';
import FileImport from '@/components/FileImport';
import AntdForm from '@/components/AntdForm';
import AdModal from '@/components/AdModal';
import ExportOSDetail from './ExportOSDetail';
import {
    filterAddFile, filterDeteteFile, queryDict, vitifyCheck,
    formatPrice, formItemFragement, formateDateToMin
} from '@/utils/common';
import prompt from '@/components/Prompt';
import {
    selectExportOSList,
    allDispatchType,
    routeUrl,
    renderTableAdSelect,
    allUrl,
    saveAllValues,
    statusList,
    containerSizeList,
    formateTime,
    formate,
} from './utils';
import styles from './exportOs.less';

const { confirm } = Modal;

@ManageList
@connect(({ exportOS, component, loading }) => ({
    exportOSList: exportOS.exportOSList,
    formValues: exportOS.formValues,
    searchValue: component.searchValue,
    customerList: component.customerList,
    dictObject: component.dictObject,
    loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class ExportOSList extends Component {
    constructor(props) {
        super(props);
        const { form } = this.props;
        this.token = localStorage.getItem('token');
        this.userToken = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
        // const { type } = this.userToken;
        this.state = {
            visible: false,
            visibleFile: false,
            visibleRecord: false,
            expandForm: false,
            recordBtnLoad: false,
            detailId: '',
            selectedRows: [],
            statusOS: '',
            importParams: { token: this.token },
            templateUrl: '',
            recordData: {},
            userType:this.userToken.type,
        };
        this.className = 'ExportOSList';
        this.fileList = [];
        // this.saveAddRecord =Form.create();
    }

    componentWillMount() { }

    componentDidMount() {
        selectExportOSList({ props: this.props });
    }
    openTrail = (e, id) => {
        router.push({
            pathname: `${routeUrl.trail}`,
            query: {
                orderNos: id,
            },
        });
    };
    getSelectList = () => {
        const { formValues } = this.props;
        selectExportOSList({ props: this.props, payload: formValues });
    };
    checkInputText = (val) => {

        const checkList = {
            'orderNumber': '订单编号', 'ocsOrderNo': '系统单号',
            'pickupDetailAddress': '发货地址', 'deliveryDetailAddress': '收货地址'
        };
        const checkArr = [
            'orderNumber', 'ocsOrderNo', 'pickupDetailAddress', 'deliveryDetailAddress'
        ]
        //有值时校验：至少输入2位
        let tipsStr = [];
        let tips = '';
        checkArr.map((v) => {
            if (val[v] && val[v].length < 2) {
                tipsStr.push(checkList[v]);
            }
        })
        if (tipsStr.length > 0) {
            tips = `查询时，${tipsStr.join('，')}至少输入2位`;
        }
        return tips;

    }
    /**
     * form 查找条件 重置
     */
    handleFormReset = () => {
        const { form } = this.props;
        const props = { props: this.props };
        saveAllValues({ payload: { formValues: {} }, ...props });
        selectExportOSList({ ...props });
    };

    /**
     * form 查找条件 查询
      // 订单编号 orderNumber (至少输入2位，全模糊)、 系统单号 ocsOrderNo (至少输入2位，全模糊)、
      // 提货（发货）地址 pickupDetailAddress (至少输入2位，全模糊)、 送货（收货）地址 deliveryDetailAddress (至少输入2位，全模糊)
     */
    handleSearch = formValues => {
        if (!formValues) return;
        const { orderDateTime, pickupDateTime, ...params } = formValues;
        if (orderDateTime && orderDateTime.length > 0) {
            params.orderDateTimeStart = moment(orderDateTime[0]).format(formate);
            params.orderDateTimeEnd = moment(orderDateTime[1]).format(formate);
        }
        if (pickupDateTime && pickupDateTime.length > 0) {
            params.pickupDateTimeStart = moment(pickupDateTime[0]).format(formate);
            params.pickupDateTimeEnd = moment(pickupDateTime[1]).format(formate);
        }

        // if(pickupCity)  params.pickupCityCode =  pickupCity[pickupCity.length - 1] || '';
        // if(deliveryCity) params.deliveryCityCode = deliveryCity[deliveryCity.length - 1] || '' ;

        const tipsText = this.checkInputText(formValues);
        if (tipsText) {
            prompt({
                content: tipsText,
                type: 'warn',
                duration: 3
            });
            return;
        }

        saveAllValues({ payload: { formValues: params }, props: this.props });
        selectExportOSList({ props: this.props, payload: params });
    };

    /**
     * table 表格 分页操作
     */
    handleStandardTableChange = param => {
        const { formValues } = this.props;
        selectExportOSList({ payload: { ...formValues, ...param }, props: this.props });
    };

    /**
     *  查看详情
     */
    showDetail = (e, record) => {
        e.stopPropagation();
        this.handleStateChange([
            { detailId: record.id },
            { statusOS: record.status },
            { visible: true },
        ]);
    };

    //新建
    handleAdd = () => {
        router.push(routeUrl.add);
    };

    //编辑
    handleEdit = () => {
        const { detailId } = this.state;
        this.handleStateChange([{ visible: false }]);
        router.push(`${routeUrl.edit}/${detailId}`);
    };

    handleStateChange = (options = []) => {
        options.map(item => {
            this.setState(item);
        });
    };

    // 删除:已受理status==1的不可删除--->删除改为取消
    cancelOrder = flag => {
        const { dispatch, formValues } = this.props;
        const { detailId, selectedRows } = this.state;
        let ids = [];
        let checkRes = false;
        if (selectedRows.length > 0 && !flag) {
            selectedRows.forEach((v) => {
                ids.push(v.id);
                if (v.status == "1" || v.status == '4') {
                    prompt({
                        content: "已受理或已取消状态不可取消，请重新选择",
                        type: 'warn'
                    });
                    checkRes = true;
                    return;
                }
            });
        }
        if (checkRes) return;
        confirm({
            title: '确定取消这条数据吗？',
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: allDispatchType.cancelOrder,
                    payload: flag ? [detailId] : ids,
                    callback: () => {
                        this.handleStateChange([{ visible: false, selectedRows: [] }]);
                        selectExportOSList({ props: this.props, payload: formValues });
                    },
                });
            },
        });
    };
    //导入
    handleImportFile = () => {
        const { visibleFile } = this.state;
        const templateUrl = this.getTemplateUrl('', 'consignorCode');
        this.setState({ visibleFile: !visibleFile });
    };
    getTemplateUrl = (val, type) => {
        const {
            customerList: { list },
        } = this.props;
        let templateUrl = '';
        if (list && list.length > 0) {
            if (list.length == 1) {
                val = list[0].consignorCode; //当只有一条数据时，默认选择第一条数据
            }
            list.map(v => {
                if (v.consignorCode == val) {
                    templateUrl = v.templateUrl;
                }
            });
        }
        const url = templateUrl ? `http://${window.location.host}/server/api/api/Common/File/GetFile?vpath=${templateUrl}` : '';
        this.setState(pre => ({
            importParams: {
                ...pre.importParams,
                [type]: val,
            },
            templateUrl: url,
        }));
    };
    changeImportFields = (val, type) => {
        this.getTemplateUrl(val, type);
    };
    //附件补录弹窗：
    fileRecordMoadl = () => {
        const { selectedRows } = this.state;
        const { dispatch } = this.props;
        let checkRes = true;
        if (selectedRows.length == 1) {
            const tips = "请选择已受理状态进行补录";
            selectedRows.forEach((v) => {
                if (v.status !== 1) {
                    prompt({
                        content: tips,
                        type: 'warn'
                    });
                    checkRes = false;
                    return;
                }
            });
        } else {
            prompt({
                content: '请选择一条数据进行补录',
                type: 'warn'
            });
            checkRes = false
            return;
        }

        if (checkRes) {
            this.setState((pre) => ({
                visibleRecord: !pre.visibleRecord
            }), () => {
                dispatch({
                    type: allDispatchType.getOrderFile,
                    payload: { orderId: selectedRows[0].id },
                    callback: (data) => {
                        const { files, remarks } = data;
                        this.fileList = files || [];
                        this.setState({
                            recordData: {
                                remarks,
                                files: files || [],
                            }
                        });
                    },
                });
            });

        };

    }
    //确认补录：  接口： 
    saveAddRecord = () => {
        //处理附件
        const { form, dispatch } = this.props;
        const { selectedRows } = this.state;
        const values = form.getFieldsValue(['files', 'remarks']);
        // form.validateFields(['files', 'remarks'], (errors, values) => {
        //   console.log('errors, values',errors, values)
        // });
        // return;
        let params = {};
        let unit = {
            handleFiles: (files, flag) => {
                let arr = [];
                if (files && files.length > 0) {
                    files.map(v => {
                        let obj = {};
                        obj.fileId = v;
                        obj.flag = flag;
                        arr.push(obj);
                    });
                }
                return arr;
            },
        };
        const addFiles = unit.handleFiles(filterAddFile(values.files), 1);
        const delFiles = unit.handleFiles(filterDeteteFile(values.files, this.fileList), 0);
        params.files = [...addFiles, ...delFiles];
        params.orderId = selectedRows[0].id;
        params.remarks = values.remarks;
        if (!values.remarks) {
            prompt({
                content: '请填写补录原因',
                type: 'error',
            });
            return;
        }
        if (addFiles.length == 0 && this.fileList.length === delFiles.length) {
            prompt({
                content: '请上传附件',
                type: 'error',
            });
            return;
        }
        dispatch({
            type: allDispatchType.operateFile,
            payload: params,
            callback: () => {
                this.handleStateChange([{ visibleRecord: false, selectedRows: [], recordData: {} }]);
                selectExportOSList({ props: this.props, payload: formValues });
            },
        });
    }

    render() {
        const {
            form,
            form: { getFieldDecorator },
            loading,
            exportOSList,
            customerList,
            isMobile,
        } = this.props;

        const {
            importParams,
            templateUrl,
            statusOS,
            visible,
            visibleRecord,
            detailId,
            selectedRows,
            visibleFile,
            expandForm,
            recordBtnLoad,
            recordData,
            userType
        } = this.state;

        const commonParams = {
            getFieldDecorator,
        };

        const columns = [
            {
                title: '订单编号',
                dataIndex: 'orderNumber',
                render: (text, record) => (
                    <a onClick={e => this.showDetail(e, record)} title={text}>
                        {text}
                    </a>
                ),
                fixed: this.props.isMobile ? false : true,
            },
           
            {
                title: '状态',
                dataIndex: 'status',
                width: 100,
                render: text =>
                    renderTableAdSelect({
                        props: this.props,
                        value: text ? text.toString() : '0',
                        data: statusList,
                    }),
            },
            {
                title: '下单时间',
                dataIndex: 'orderDateTime',
                render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
            },
            {
                title: '提货时间',
                dataIndex: 'pickupDateTime',
                render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
            },
            {
                title: '系统单号',
                dataIndex: 'ocsOrderNo',
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '发货人',
                dataIndex: 'customerName',
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '发货城市',
                dataIndex: 'pickupCity',
                width: 120,
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '发货地址',
                dataIndex: 'pickupDetailAddress',
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '收货人',
                dataIndex: 'consigneeName',
                width: 150,
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '收货城市',
                dataIndex: 'deliveryCity',
                width: 120,
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '收货地址',
                dataIndex: 'deliveryDetailAddress',
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '委托方',
                dataIndex: 'consignorName',
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '业务类型',
                dataIndex: 'businessType',
                width: 150,
                render: text => <span title={text}>{text}</span>,
            },
            {
                title: '贸易条款',
                dataIndex: 'incoterm',
                width: 80,
                render: text => <span title={text}>{text}</span>,
            },
    
            {
                title: '联络人',
                dataIndex: 'contactPerson',
            },
    
            {
                title: '联络号码',
                dataIndex: 'contactNumber',
            },
            {
                title: '报关服务',
                dataIndex: 'isCustomDeclaration',
                width: 80,
                render: (text, record) => <span>{text ? '是' : '否'}</span>,
            },
            {
                title: '出口买单',
                dataIndex: 'isExportBillsPurchase',
                width: 80,
                render: (text, record) => <span>{text ? '是' : '否'}</span>,
            },
            {
                title: '驳回人',
                dataIndex: 'rejectBy',
                width: 100,
                render: (text, record) => <span title={text}>{text}</span>,
            },
            {
                title: '驳回次数',
                dataIndex: 'rejectCount',
                width: 80,
                render: (text, record) => <span>{text}</span>,
            },
            {
                title: '驳回时间',
                dataIndex: 'rejectTime',
                render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
            },
            {
                title: '驳回原因',
                dataIndex: 'rejectReason',
                render: (text, record) => <span title={text}>{text}</span>,
            },
            {
                title: '吨车/货柜尺寸',
                dataIndex: 'truckType',
                render: text =>
                    renderTableAdSelect({
                        props: this.props,
                        value: text,
                        data: containerSizeList,
                    }),
            },
        ];

        if(userType !=='S' ){
            columns.splice(1,0,
                {
                    title: '轨迹',
                    dataIndex: 'trail',
                    width: 60,
                    render: (text, record) => {
                        return (
                            <a title={'查看轨迹'} onClick={e => this.openTrail(e, record.orderNumber)}>
                                <Icon type="environment" />
                            </a>
                        );
                    },
            })
        }
       
        const firstFormItem = (
            <AntdFormItem label="订单编号" code="orderNumber" {...commonParams}>
                <AntdInput />
            </AntdFormItem>
        );
        const secondFormItem = (
            <AntdFormItem label="系统单号" code="ocsOrderNo" {...commonParams}>
                <AntdInput />
            </AntdFormItem>

        );

        // secondForm
        const otherFormItem = [
            [
                <AntdFormItem label="货柜尺寸" code="truckType" {...commonParams}>
                    <AdSelect isExist={true} data={containerSizeList} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem label="下单时间" code="orderDateTime" {...commonParams}>
                    <AntdDatePicker placeholder="请选择时间" mode="range" />
                </AntdFormItem>,
                <AntdFormItem label="提货时间" code="pickupDateTime" {...commonParams}>
                    <AntdDatePicker placeholder="请选择时间" mode="range" />
                </AntdFormItem>,
                <AntdFormItem label="发货地址" code="pickupDetailAddress" {...commonParams}>
                    <AntdInput />
                </AntdFormItem>,
                // <AntdFormItem label="发货人" code="customerName" {...commonParams}>
                //   <AntdInput />
                // </AntdFormItem>
            ],
            [
                <AntdFormItem label="收货地址" code="deliveryDetailAddress" {...commonParams}>
                    <AntdInput />
                </AntdFormItem>,
                <AntdFormItem label="发货城市" code="pickupCity" {...commonParams}>
                    <AntdInput />
                </AntdFormItem>,
                <AntdFormItem label="收货城市" code="deliveryCity" {...commonParams}>
                    <AntdInput />
                </AntdFormItem>,
            ],
            ['operatorButtons']
        ];

        const selectFormParams = {
            firstFormItem,
            secondFormItem,
            otherFormItem,
            form,
            className: this.className,
            handleFormReset: this.handleFormReset,
            handleSearch: this.handleSearch,
            toggleForm: expandForm => {
                this.handleStateChange([{ expandForm }]);
            },
        };

        const tableButtonsParams = {
            handleAdd: this.handleAdd,
            code: 'operate',
            pagination: exportOSList.pagination,
            buttons: (
                <Fragment>
                    <AdButton
                        disabled={!selectedRows.length > 0}
                        onClick={() => this.cancelOrder()}
                        text="取消"
                        ghost
                        type="danger"
                        code='operate'
                    />
                    <AdButton code='operate' style={{ marginLeft: 8 }} onClick={() => this.handleImportFile()} text="导入" />
                    <AdButton
                        code='operate'
                        disabled={!selectedRows.length > 0 || selectedRows.length > 1}
                        style={{ marginLeft: 8 }} onClick={() => this.fileRecordMoadl()} text="附件补录" />
                </Fragment>
            ),
        };
        // 详情 参数
        const rightDrawParams = {
            isMobile,
            visible,
            title: '订单详情',
            closeDetail: () => {
                this.handleStateChange([{ visible: false }]);
            },
            buttons: (
                <span>
                    <AdButton
                        disabled={statusOS === 1}
                        onClick={() => this.cancelOrder(1)}
                        text="取消"
                        ghost
                        type="danger"
                        code='operate'
                    />
                    <AdButton
                        code='operate'
                        disabled={statusOS === 1}
                        onClick={this.handleEdit}
                        style={{ marginLeft: 8 }}
                        type="primary"
                        text="编辑"
                    />
                </span>
            ),
        };

        const formItem = [
            [
                <AntdFormItem
                    label="委托方"
                    code="consignorCode"
                    initialValue={
                        customerList.list && customerList.list.length == 1
                            ? customerList.list[0].consignorCode
                            : undefined
                    }
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <AdSelect
                        isExist={true}
                        show={{ id: 'consignorCode', name: 'consignorName' }}
                        data={customerList.list || []}
                        style={{ width: 250 }}
                        onChange={val => this.changeImportFields(val, 'consignorCode')}
                    />
                </AntdFormItem>,
            ],
        ];
        const formItemRecord = [
            [
                <AntdFormItem
                    label="补录原因"
                    code="remarks"
                    rules={[
                        { required: true },
                        {
                            validator: (rule, value, callback) => {
                                checkStrLength(rule, value, callback, 500, '补录原因');
                            },
                        },
                    ]}
                    initialValue={recordData.remarks}
                    {...commonParams}
                >
                    <AntdInput
                        width="100%"
                        maxlen={500}
                        type="textarea"
                        placeholder="请输入..."
                        style={{ width: '100%' }}
                    />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="附件"
                    code="files"
                    rules={[{ required: true }]}
                    initialValue={recordData.files || []}
                    {...commonParams}
                >
                    <FileReader urlType="tms" disabled={false}
                    // showUpload={1 ? false : true} 
                    />
                </AntdFormItem>,
            ],
        ]
        return (
            <Fragment>
                <FileImport
                    visibleFile={visibleFile}
                    handleCancel={() => {
                        this.handleImportFile();
                    }}
                    urlImport={`api/OCS/Order/ImportOrder?${stringify(importParams)}`}
                    // urlCase={`http://10.48.3.174:66/api/Common/File/GetFile?vpath=C9E4D6D5-DD58-4C8F-A747-FAF4FDB4490F`}
                    urlCase={templateUrl}
                    queryData={[this.getSelectList]}
                    accept=".xls,.xlsx"
                    htmlForm={<AntdForm>{formItemFragement(formItem)}</AntdForm>}
                    requiredParams={{
                        required: true,
                        params: importParams.consignorCode ? true : false,
                    }}
                />
                {visibleRecord && (
                    <AdModal
                        visible={visibleRecord}
                        title={`附件补录`}
                        onOk={this.saveAddRecord}
                        onCancel={() => {
                            this.setState((pre) => ({
                                visibleRecord: !pre.visibleRecord,
                                recordData: {},
                            }));
                        }}
                        width="60%"
                        style={{
                            maxWidth: 600
                        }}
                        confirmLoading={recordBtnLoad}
                    >
                        <div className={styles.cusModal}>
                            <AntdForm>{formItemFragement(formItemRecord)}</AntdForm>
                        </div>
                    </AdModal>
                )}
                <SelectForm {...selectFormParams} />
                <TableButtons {...tableButtonsParams} />
                <StandardTable
                    loading={loading}
                    data={exportOSList}
                    selectedRows={selectedRows}
                    onSelectRow={selectedRows => {
                        this.handleStateChange([{ selectedRows }]);
                    }}
                    columns={columns}
                    onPaginationChange={this.handleStandardTableChange}
                    expandForm={expandForm}
                    className={this.className}
                    code="page"
                />
                <RightDraw {...rightDrawParams}>
                    <ExportOSDetail id={detailId} closeDetail={this.handleStateChange} />
                </RightDraw>
            </Fragment>
        );
    }
}
